import request from "../../utils/request"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    did: null,
    productList: [],
    productSpecList: [],
    show: false,
    showType: '',
    sku: {},
    targetProduct: {},
    count: 1
  },
  countChange(e){
    console.log(e);
    this.setData({
      count: e.detail
    })
  },
  addOrder() {
    wx.setStorageSync('addOrder', [{
      productSku:this.data.targetProduct,
      quantity: this.data.count
    }]);
    wx.navigateTo({
      url: '/pages/createOrder/createOrder',
    })
  },
  async addCart() {
    const res = await request.post('/cart', {
      userId: wx.getStorageSync('userInfo').id,
      quantity: this.data.count,
      productSkuId: this.data.targetProduct.id
    })
    console.log(res);
  },
  setShow(e) {
    const {
      type = ''
    } = e.currentTarget.dataset;
    this.setData({
      showType: type,
      show: !this.data.show
    })
  },
  skuto() {
    const sku = JSON.stringify(this.data.sku);
    // console.log(sku);
    const target = this.data.productList.find(item => {
      const specValues = JSON.parse(item.specValues);
      const newspecValues = {};
      for (const key in this.data.sku) {
        newspecValues[key] = specValues[key]
      }
      // console.log(JSON.stringify(newspecValues));
      return sku === JSON.stringify(newspecValues)
    })
    if (target) {
      this.setData({
        targetProduct: target
      })
    }
    console.log(target);
  },
  selectSku(e) {
    const {
      key,
      value
    } = e.currentTarget.dataset;
    const sku = Object.assign({}, this.data.sku);
    sku[key] = value;
    this.setData({
      sku
    })
    this.skuto();
  },
  async getDetail() {
    const res = await request.get(`/product_sku/${this.data.did}`);
    console.log(res.data.data.productList);
    console.log(res.data.data.productSpecList);
    const sku = {};
    res.data.data.productSpecList.forEach(item => {
      sku[item.name] = item.productSpecValueList[0].value;
    })
    console.log(sku);
    this.setData({
      sku,
      productList: res.data.data.productList,
      productSpecList: res.data.data.productSpecList
    })
    this.skuto();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.did = options.id;
    this.getDetail();
    console.log(options.id);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})